package jxta.chat.entities;


import jxta.chat.util.Constants;
import jxta.chat.util.Constants.MessageParamsKeys;
import net.jxta.endpoint.Message;
import net.jxta.endpoint.MessageElement;
import net.jxta.endpoint.StringMessageElement;

/**
 * An abstarct class that is a superclass for all other messages classes
 * in the system.
 *
 */
public abstract class AbstractMessage {

	public final static String MESSAGE_NAME_SPACE = "msg";
	//public final static String MESSAGE_PEER_DATA = "PeerData";
	
	protected Message msg;
	
	public AbstractMessage(){
		
	}
	
	public AbstractMessage(Message msg){
		this.msg = msg;
	}
	
	public final Message getMessage(){
		return msg;
	}
	
	/**
	 * Create a new general Message containing the peer name and the 
	 * message type
	 * @param params TODO
	 * 
	 * @return a message that contains the peer name and message type returned
	 * from calling getMessageType procedure
	 */
	public Message createMessage(MessageParams params){
		
		Message retVal = new Message();
		
		MessageElement me = new StringMessageElement(Constants.MESSAGE_TYPE_SPACE, this.getMessageType(), null);
		retVal.addMessageElement(me);
		
		// TODO Delete the remarks
		
		//try {
		me = new StringMessageElement(Constants.NAME_ATTRIBUTE, params.getParameter(MessageParamsKeys.NAME).toString(), null);
		
		retVal.addMessageElement(me);
		/*} catch (UnsupportedEncodingException e) {
			System.out.println("Error creating AbstractMessage name element. error: ");
			e.printStackTrace();
		}*/
		
		return msg = retVal;
	}
	
	/**
	 * Returns the peer name from the given message or null if there isn't a name.
	 * 
	 * @param msg the message that we want to get the peer name from
	 * @return the peer name from the message or null if there isn't a name
	 */
	public final String getPeerName(){
		
		return msg.getMessageElement(Constants.NAME_ATTRIBUTE) != null ? msg.getMessageElement(Constants.NAME_ATTRIBUTE).toString() :
															   null;
		
	}
	
	public Object getAttributeValue(String attribute){
		return msg.getMessageElement(attribute) != null ? msg.getMessageElement(attribute).toString() : null;
	}
	
	public abstract String getMessageType();
	
}
